/**
 * Ant Design Pro v4 use `@ant-design/pro-layout` to handle Layout.
 * You can view component api by:
 * https://github.com/ant-design/ant-design-pro-layout
 */
import ProLayout, {
  MenuDataItem,
  BasicLayoutProps as ProLayoutProps,
  Settings,
  DefaultFooter,
} from '@ant-design/pro-layout';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
  Link,
  useIntl,
  connect,
  Dispatch,
  history,
  useRequest,
  useRouteMatch,
  matchPath,
  useAccess,
} from 'umi';
import { GithubOutlined } from '@ant-design/icons';
import { Result, Button, Spin } from 'antd';
import Authorized from '@/utils/Authorized';
import RightContent from '@/components/GlobalHeader/RightContent';
import { ConnectState } from '@/models/connect';
import { getMatchMenu } from '@umijs/route-utils';
import logo from '../assets/logo.svg';
import { getRouters } from '@/services/user';

import _ from 'lodash';

export interface BasicLayoutProps extends ProLayoutProps {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
  route: ProLayoutProps['route'] & {
    authority: string[];
  };
  settings: Settings;
  dispatch: Dispatch;
  routes: Array<any>;
}
export type BasicLayoutContext = { [K in 'location']: BasicLayoutProps[K] } & {
  breadcrumbNameMap: {
    [path: string]: MenuDataItem;
  };
};
/**
 * use Authorized check all menu item
 */

function checkAuth(path: string): boolean {
  return true;
}

// const menuDataRender = (menuList: MenuDataItem[]): MenuDataItem[] => {

//   console.log('menuList')
//   console.log(menuList)

//   let list = menuList.map((item) => {
//     const localItem = {
//       ...item,
//       children: item.children ? menuDataRender(item.children) : undefined,
//     };
//     return Authorized.check(item.authority, localItem, null) as MenuDataItem;
//   });

//   console.log('list')
//   console.log(list)
//   return list
// }
const menuDataRender = (menuList) => {
  if (menuList) {
    return menuList.map((item) => {
      item.hideInMenu = item.hidden;
      if (item.children) menuDataRender(item.children);
      return item;
    });
  } else {
    return [];
  }
};

const defaultFooterDom = (
  <DefaultFooter
    copyright={`${new Date().getFullYear()} 蚂蚁集团体验技术部出品`}
    links={[
      {
        key: 'Ant Design Pro',
        title: 'Ant Design Pro',
        href: 'https://pro.ant.design',
        blankTarget: true,
      },
      {
        key: 'github',
        title: <GithubOutlined />,
        href: 'https://github.com/ant-design/ant-design-pro',
        blankTarget: true,
      },
      {
        key: 'Ant Design',
        title: 'Ant Design',
        href: 'https://ant.design',
        blankTarget: true,
      },
    ]}
  />
);

// 将路由信息拍平
export function flattenTree<T>(tree: T[], childResolver: { (t: T): T[] | undefined }): T[] {
  return tree.reduce((newTree, t) => {
    const child = childResolver(t);
    newTree.push(t);
    if (child) {
      newTree.push(...flattenTree(child, childResolver));
    }
    return newTree;
  }, [] as T[]);
}

const BasicLayout: React.FC<BasicLayoutProps> = (props) => {
  const {
    dispatch,
    children,
    settings,
    location = {
      pathname: '/',
    },
    routes,
  } = props;

  const menuDataRef = useRef<MenuDataItem[]>([]);

  useEffect(() => {}, []);
  /**
   * init variables
   */

  const { data: menuData, loading: menuLoading } = useRequest(getRouters);

  const handleMenuCollapse = (payload: boolean): void => {
    if (dispatch) {
      dispatch({
        type: 'global/changeLayoutCollapsed',
        payload,
      });
    }
  };
  // get children authority
  const authorized = useMemo(
    () =>
      getMatchMenu(location.pathname || '/', menuDataRef.current).pop() || {
        authority: undefined,
      },
    [location.pathname],
  );

  const { formatMessage } = useIntl();

  const routersTemp = _.cloneDeep(routes);
  const matchedRoute = flattenTree(routersTemp, (r) => r.routes)
    .filter((route) => !!route.path)
    .map((m) => {
      m.exact = true;
      return m;
    })
    .find((m) => matchPath(location.pathname as string, m as any));
  // console.log('matchedRoute');
  // console.log(
  //   flattenTree(routersTemp, (r) => r.routes)
  //     .filter((route) => !!route.path)
  //     .map((m) => {
  //       m.exact = true;
  //       return m;
  //     }),
  // );
  // console.log(routersTemp);
  // console.log(location.pathname);
  // console.log(matchedRoute);

  const access = useAccess();

  return (
    <ProLayout
      logo={logo}
      formatMessage={formatMessage}
      onCollapse={handleMenuCollapse}
      onMenuHeaderClick={() => history.push('/')}
      menuItemRender={(menuItemProps, defaultDom) => {
        if (menuItemProps.isUrl || !menuItemProps.path) {
          return defaultDom;
        }
        return <Link to={menuItemProps.path}>{defaultDom}</Link>;
      }}
      breadcrumbRender={(routers = []) => [
        {
          path: '/',
          breadcrumbName: formatMessage({ id: 'menu.home' }),
        },
        ...routers,
      ]}
      itemRender={(route, params, routes, paths) => {
        // const first = routes.indexOf(route) === 0;
        // console.log('itemRender')
        // console.log(route)
        // console.log(routes)
        // console.log(paths)
        // console.log(first)

        return <Link to={route.path}>{route.breadcrumbName}</Link>;
        // return first ? (
        //   <Link to={paths.join('/')}>{route.breadcrumbName}</Link>
        // ) : (
        //   <span>{route.breadcrumbName}</span>
        // );
      }}
      footerRender={() => defaultFooterDom}
      menuContentRender={(_, dom) =>
        menuLoading ? (
          <div
            style={{
              padding: '24px 0',
            }}
          >
            <Spin tip="菜单加载中">{dom}</Spin>
          </div>
        ) : (
          dom
        )
      }
      menuDataRender={() => {
        if (menuLoading) {
          return [];
        } else {
          return menuDataRender(menuData);
        }
      }}
      rightContentRender={() => <RightContent />}
      postMenuData={(menuData) => {
        menuDataRef.current = menuData || [];
        return menuData || [];
      }}
      {...props}
      {...settings}
    >
      {/* <Authorized authority={authorized!.authority} noMatch={noMatch}>
        {children}
      </Authorized> */}
      {/* 路由权限判断 */}
      {!matchedRoute ? (
        <Result status={404} title="404" subTitle="对不起，您所访问的页面不存在！" />
      ) : matchedRoute.access ? (
        access[matchedRoute.access] ? (
          children
        ) : (
          <Result status={403} title="403" subTitle="对不起，您无权访问该页面！" />
        )
      ) : (
        children
      )}
    </ProLayout>
  );
};

export default connect(({ global, settings, ...props }: ConnectState) => ({
  collapsed: global.collapsed,
  settings,
  props,
}))(BasicLayout);
